import React from "react";
import { getPinyin } from "@/common/pinyin-pro";
import { cookies } from "next/headers";

interface PinyinTextProps {
  text: string;
  fontSize?: number; // 字体大小，单位为rem
  pyFontSize?: number; // 拼音字体大小，单位为rem
  overflow?: boolean|'auto'; // 是否允许溢出
  textAlign?: 'left' | 'center' | 'right'; // 文本对齐方式
}

const PinyinText: React.FC<PinyinTextProps> =  async ({ 
  text, 
  fontSize = 1, 
  pyFontSize,
  overflow='auto',
  textAlign='left',
}) => {
  const cookieStore = await cookies();
  const showPinyin = cookieStore.get('pinyin')?.value !== '1';
  if (!showPinyin) {
    return text;
  }
  // 将文本拆分为单个字符进行处理
  const characters = text.split("");
  
  // 创建结果数组
  const result = [];
  
  // 逐个处理字符
  for (let i = 0; i < characters.length; i++) {
    const char = characters[i];
    const charCode = char.charCodeAt(0);
    
    // 判断是否是中文字符 (Unicode范围)
    const isChinese = charCode >= 0x4e00 && charCode <= 0x9fff;
    
    if (isChinese && showPinyin) {
      // 获取汉字的拼音
      const pinyin = getPinyin(char);
      result.push({
        char,
        pinyin,
        isChinese: true
      });
    } else {
      // 非中文字符或不显示拼音
      result.push({
        char,
        pinyin: "",
        isChinese: false
      });
    }
  }

  // 计算字符宽度，确保一致性
  const charWidth = `${fontSize*1.5 + (pyFontSize?0:0.3)}rem`;
  const pinyinFontSize = `${pyFontSize||(fontSize*2/3)}rem`;

  return (
    <div className={`inline-flex gap-0 gap-y-2 ${overflow==='auto'?'flex-wrap md:flex-nowrap md:overflow-hidden':overflow?'flex-nowrap overflow-hidden':'flex-wrap'} ${textAlign==='center'?'justify-center': textAlign==='right'?'justify-end':''}`}>
      {result.map((item, idx) => (
        <div 
          key={idx} 
          className={`flex flex-col items-center ${item.isChinese ? "justify-start" : "justify-end"}`}
          style={{ 
            width: item.isChinese?charWidth:`${fontSize}rem`,
            minWidth: item.isChinese?charWidth:`${fontSize}rem`,
          }}
        >
          {item.isChinese && (
            <span 
              className="w-full text-center flex items-center justify-center"
              style={{ 
                fontSize: pinyinFontSize,
                height: `${fontSize/2}rem`,
              }}
            >
              {item.pinyin}
            </span>
          )}
          <span 
            className="text-center w-full mt-[0.1rem]"
            style={{ 
              fontSize: `${fontSize}rem`,
            }}
          >
            {item.char}
          </span>
        </div>
      ))}
    </div>
  );
};

export default PinyinText;